package com.compass.mobile.ui.fragment

import LogUtil
import UserInfoManager
import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import androidx.fragment.app.activityViewModels
import androidx.leanback.widget.ArrayObjectAdapter
import androidx.leanback.widget.FocusHighlight
import androidx.leanback.widget.FocusHighlightHelper
import com.compass.mobile.R
import com.compass.mobile.callback.OnItemClickListener
import com.compass.mobile.databinding.FrgamentHomePageBinding
import com.compass.mobile.framework.base.BaseVBFragment
import com.compass.mobile.framework.constant.EVENT_TYPE_ACCOUNT_RECHARGE
import com.compass.mobile.framework.constant.EVENT_TYPE_APPLY_PRESCRIPTION
import com.compass.mobile.framework.constant.EVENT_TYPE_APPOINTMENT
import com.compass.mobile.framework.constant.EVENT_TYPE_APPOINTMENT_CHECK
import com.compass.mobile.framework.constant.EVENT_TYPE_APPOINTMENT_INSPECT
import com.compass.mobile.framework.constant.EVENT_TYPE_ARTICLE_DETAIL
import com.compass.mobile.framework.constant.EVENT_TYPE_COMFORT_CARE
import com.compass.mobile.framework.constant.EVENT_TYPE_COMPLAINT_SUGGESTION
import com.compass.mobile.framework.constant.EVENT_TYPE_DEPARTMENT_INTRODUCTION
import com.compass.mobile.framework.constant.EVENT_TYPE_DEPARTMENT_LIST
import com.compass.mobile.framework.constant.EVENT_TYPE_HOSPITALIZATION_EXPENSES
import com.compass.mobile.framework.constant.EVENT_TYPE_INDEPENDENT_BILLING
import com.compass.mobile.framework.constant.EVENT_TYPE_INTELLIGENT_GUIDANCE
import com.compass.mobile.framework.constant.EVENT_TYPE_MALL_ONLINE
import com.compass.mobile.framework.constant.EVENT_TYPE_MEDICAL_RECORD
import com.compass.mobile.framework.constant.EVENT_TYPE_MY_DOCTOR
import com.compass.mobile.framework.constant.EVENT_TYPE_MY_PRESCRIPTION
import com.compass.mobile.framework.constant.EVENT_TYPE_ONLINE_MEDICAL
import com.compass.mobile.framework.constant.EVENT_TYPE_OUTPATIENT_PAYMENT
import com.compass.mobile.framework.constant.EVENT_TYPE_REPORT_QUERY
import com.compass.mobile.framework.constant.PATIENT_SWITCH
import com.compass.mobile.framework.ext.onClick
import com.compass.mobile.framework.utils.FocusViewUtils
import com.compass.mobile.framework.utils.LiveDataBus
import com.compass.mobile.framework.utils.dpToPx
import com.compass.mobile.models.Doctor
import com.compass.mobile.models.HomeMenuItem
import com.compass.mobile.models.PatientBean
import com.compass.mobile.presenters.SpecialColumnPresenter
import com.compass.mobile.ui.activity.CaseHistoryRecordActivity
import com.compass.mobile.ui.activity.ComplaintActivity
import com.compass.mobile.ui.activity.ComplaintNewActivity
import com.compass.mobile.ui.activity.DepartmentFragmentActivity
import com.compass.mobile.ui.activity.DoctorHomePageActivity
import com.compass.mobile.ui.activity.DoctorSpecialColumnActivity
import com.compass.mobile.ui.activity.FollowingPrescriptionActivity
import com.compass.mobile.ui.activity.HomeCareActivity
import com.compass.mobile.ui.activity.HomePageActivity
import com.compass.mobile.ui.activity.IndependentBillingActivity
import com.compass.mobile.ui.activity.IntelligentGuidanceActivity
import com.compass.mobile.ui.activity.MyAppointmentActivity
import com.compass.mobile.ui.activity.MyInspectionActivity
import com.compass.mobile.ui.activity.NotificationActivity
import com.compass.mobile.ui.activity.PatientsActivity
import com.compass.mobile.ui.activity.PrescriptionRecordActivity
import com.compass.mobile.ui.activity.RecommendedDoctorActivity
import com.compass.mobile.ui.dialog.CommonMessageDialog
import com.compass.mobile.ui.viewModel.MainViewModel
import com.compass.mobile.widget.MyBridgeAdapter
import com.netease.nimlib.sdk.NIMClient
import com.netease.nimlib.sdk.RequestCallback
import com.netease.nimlib.sdk.auth.AuthService
import com.netease.nimlib.sdk.auth.LoginInfo
import getStringFromResource
import setUrl
import toJson


/**
 * Description：首页
 * Date:2024/5/15 9:41
 */
class HomePageFragment : BaseVBFragment<FrgamentHomePageBinding>() {
    private val mainViewModel: MainViewModel by activityViewModels()
    private var doctors: MutableList<Doctor> = mutableListOf()
    private lateinit var arrayObjectAdapter: ArrayObjectAdapter
    override fun initView(view: View, savedInstanceState: Bundle?) {
        mBinding?.specialColumn?.post {
            // 使用获取到的宽度
            val width = mBinding?.specialColumn?.width
            width?.let {
                specialColumn(it)
            }
        }
        FocusViewUtils.scaleView(mBinding?.llInquiry, 0)
        FocusViewUtils.scaleView(mBinding?.backlog, 0)
        FocusViewUtils.scaleView(mBinding?.llAppointment, 0)
        FocusViewUtils.scaleView(mBinding?.llIndependentBilling, 0)
        FocusViewUtils.scaleView(mBinding?.llSwitchPatients, 0)
        FocusViewUtils.scaleView(mBinding?.llNurse, 0)
        FocusViewUtils.scaleView(mBinding?.llMail, 0)
        FocusViewUtils.scaleView(mBinding?.llBookingRegister, 0)
        FocusViewUtils.scaleView(mBinding?.llFollowing, 0)
        FocusViewUtils.scaleView(mBinding?.tvMore, 0)
    }

    override fun initData() {
        showLoading()
        mainViewModel.getMenuConfig()
        mainViewModel.getDefPatient()
        mainViewModel.getAllDictionaries()
        mainViewModel.geRecommendDoctor()
        mainViewModel.patientDefLiveData.observe(this) {
            dismissLoading()
            it?.let { bean ->
                UserInfoManager.savePatientInfo(bean.toJson())
                val homePageActivity = activity as HomePageActivity
                homePageActivity.setDefaultPatientView()
                doLoginIM(bean)
            } ?: kotlin.run {
                UserInfoManager.savePatientInfo("")
            }
        }
        LiveDataBus.get().with(PATIENT_SWITCH, String::class.java)
            .observe(this) {
                //退出当前登录的就诊人
                NIMClient.getService(AuthService::class.java).logout()
                //刷新一次就诊人
                mainViewModel.getDefPatient()
            }
        mainViewModel.allDictionariesLiveData.observe(this) {
            it?.let { warp ->
                UserInfoManager.saveNotificationType(warp.patient_with_treatment_system_messages_type.toJson())
                UserInfoManager.saveOrderType(warp.order_consultation_status.toJson())
                UserInfoManager.saveOrderConsultationType(warp.order_consultation_type.toJson())
                UserInfoManager.saveInspectionReportType(it.inspection_report_type.toJson())
                UserInfoManager.saveOrderNurseStatusType(it.order_nurse_status.toJson())
                UserInfoManager.saveInspectionType(it.order_inspection_status.toJson())
            }
        }
        mainViewModel.doctorsLiveData.observe(this) {
            arrayObjectAdapter.clear()
            it?.let {
                doctors=it
                arrayObjectAdapter.addAll(0,doctors)
            }
        }
        mainViewModel.homePageWarp.observe(this){
            if(it!=null){
                mBinding?.apply {
                    //左侧菜单
//                    tvLeftFirstTitle.text = it.homeLeftFirst.title
//                    tvLeftFirstContent.text = it.homeLeftFirst.description
                    ivLeftFirst.setUrl(it.homeLeftFirst.background)

//                    tvLeftSecondTitle.text = it.homeLeftSecond.title
//                    tvLeftSecondContent.text = it.homeLeftSecond.description
                    ivLeftSecond.setUrl(it.homeLeftSecond.background)

//                    tvLeftThirdTitle.text = it.homeLeftThird.title
//                    tvLeftThirdContent.text = it.homeLeftThird.description
                    ivLeftThird.setUrl(it.homeLeftThird.background)


                    ivBottomFirst.setUrl(it.homeBottomFirst.background)

                    //右侧菜单
//                    tvHomeRightFirst.text = it.homeRightFirst.title
                    ivRightFirst.setUrl(it.homeRightFirst.background)

//                    tvHomeRightSecond.text = it.homeRightSecond.title
                    ivRightSecond.setUrl(it.homeRightSecond.background)

//                    tvHomeRightThird.text = it.homeRightThird.title
                    ivRightThird.setUrl(it.homeRightThird.background)

//                    tvHomeRightFourthly.text = it.homeRightFourthly.title
                    ivRightFourthly.setUrl(it.homeRightFourthly.background)

                    //中间菜单
//                    tvHomeMain.text = it.homeMainMenu.title
//                    tvHosTip.text = it.homeMainMenu.description
                    ivHomeMain.setUrl(it.homeMainMenu.background)
                }
            }
        }

    }

    private fun menuClick(meunItem:HomeMenuItem){
        when(meunItem.linkType){
            //内部页面
            1-> goAppPage(meunItem)

            //医生专栏
            2->{}
//                DoctorSpecialColumnActivity.start(requireContext())

            //切换就诊人
            3->{
                if (!UserInfoManager.isHaveDefPatient()) {
                    addPatientDialog()
                    return
                }
                PatientsActivity.start(requireContext())
            }
            //待办事项
            4->{
//                if (!UserInfoManager.isHaveDefPatient()) {
//                    addPatientDialog()
//                    return
//                }
                if (!UserInfoManager.isHaveDefPatient()) {
                    addPatientDialog()
                    return
                }
                NotificationActivity.start(requireContext())
            }
        }
    }

    /**
     * 内部页面跳转事件
     * 1.科室列表 2.我的医生 3.病案邮寄 4.我的处方 5.申请处方 6.安心护理 7.在线商城 8.预约挂号 9.门诊缴费
     * 10.报告查询 11.住院费用 12.账户充值 13.预约检查 14预约检验 15在线问诊 16.文章详情 17.科室介绍 18 自主开单
     * 19.投诉建议 20.智能导诊
     */
    private fun goAppPage(item:HomeMenuItem){
        if (!UserInfoManager.isHaveDefPatient()) {
            addPatientDialog()
            return
        }
        when (item.linkPagePath) {
            EVENT_TYPE_DEPARTMENT_LIST ->   DepartmentFragmentActivity.start(requireContext(),"booking")
            EVENT_TYPE_MY_DOCTOR -> RecommendedDoctorActivity.start(requireContext())
            EVENT_TYPE_MEDICAL_RECORD ->  CaseHistoryRecordActivity.start(requireContext())
            EVENT_TYPE_MY_PRESCRIPTION ->   PrescriptionRecordActivity.start(requireContext())
            EVENT_TYPE_APPLY_PRESCRIPTION -> FollowingPrescriptionActivity.start(requireContext())
            EVENT_TYPE_COMFORT_CARE ->  HomeCareActivity.start(requireContext())
            EVENT_TYPE_MALL_ONLINE -> {}
            EVENT_TYPE_APPOINTMENT ->  DepartmentFragmentActivity.start(requireContext(), "booking")
            EVENT_TYPE_OUTPATIENT_PAYMENT -> {}
            EVENT_TYPE_REPORT_QUERY -> {}
            EVENT_TYPE_HOSPITALIZATION_EXPENSES -> {}
            EVENT_TYPE_ACCOUNT_RECHARGE -> {}
            EVENT_TYPE_APPOINTMENT_CHECK ->    MyAppointmentActivity.start(requireContext())
            EVENT_TYPE_APPOINTMENT_INSPECT ->   MyAppointmentActivity.start(requireContext())
            EVENT_TYPE_ONLINE_MEDICAL -> DepartmentFragmentActivity.start(requireContext(), "inquiry")
            EVENT_TYPE_ARTICLE_DETAIL -> {}
            EVENT_TYPE_DEPARTMENT_INTRODUCTION -> {}
            EVENT_TYPE_INDEPENDENT_BILLING -> IndependentBillingActivity.start(requireContext())
            EVENT_TYPE_COMPLAINT_SUGGESTION -> ComplaintNewActivity.start(requireContext())
            EVENT_TYPE_INTELLIGENT_GUIDANCE -> IntelligentGuidanceActivity.start(requireContext())
        }

    }

    private val onItemClickListener: OnItemClickListener = object : OnItemClickListener {
        override fun onItemClick(position: Int, view: View) {
            val item=doctors[position]

            item.departmentId?.let {
                DoctorHomePageActivity.start(requireContext(),item.id,it)
            }?:kotlin.run {
                 showToast("医生信息异常，请联系客服")
            }

        }
    }

    @SuppressLint("RestrictedApi")
    fun specialColumn(width: Int) {
        val finalWidth = width - dpToPx(30)
        val specialColumnPresenter =
            SpecialColumnPresenter()
        specialColumnPresenter.setFinalWidth(finalWidth / 3)
        arrayObjectAdapter = ArrayObjectAdapter(specialColumnPresenter)
        val itemBridgeAdapter =
            MyBridgeAdapter(requireContext(), arrayObjectAdapter, onItemClickListener)
        mBinding?.specialColumn?.setAdapter(itemBridgeAdapter)


        arrayObjectAdapter.addAll(0, doctors)
        //设置放大级别 为最低1.06%
        FocusHighlightHelper.setupBrowseItemFocusHighlight(
            itemBridgeAdapter, FocusHighlight.ZOOM_FACTOR_SMALL, false
        )

    }

    private fun addPatientDialog() {
        CommonMessageDialog.Builder(requireActivity())
            .setTitle("温馨提示")
            .setMessage("您还没有添加就诊人，是否去添加？")
            .setConfirm(getStringFromResource(R.string.default_confirm))
            .setCancel(getString(R.string.default_cancel))
            .setonCancelListener {
                it?.dismiss()
            }
            .setonConfirmListener {
                PatientsActivity.start(requireContext())
                it?.dismiss()
            }.create().show()
    }


    override fun intListener() {
        mBinding?.tvMore?.onClick {
            RecommendedDoctorActivity.start(requireContext())
        }
        //左边第一个
        mBinding?.backlog?.onClick {
//            if (!UserInfoManager.isHaveDefPatient()) {
//                addPatientDialog()
//                return@onClick
//            }
//            NotificationActivity.start(requireContext())
            mainViewModel.homePageWarp.value?.let { it1 -> menuClick(it1.homeLeftFirst) }
        }

        //左边第二个
        mBinding?.llAppointment?.onClick {
            mainViewModel.homePageWarp.value?.let { it1 -> menuClick(it1.homeLeftSecond) }
//            if (!UserInfoManager.isHaveDefPatient()) {
//                addPatientDialog()
//                return@onClick
//            }
//
//            MyAppointmentActivity.start(requireContext())
        }
        //左边第三个
        mBinding?.llIndependentBilling?.onClick {
            mainViewModel.homePageWarp.value?.let { it1 -> menuClick(it1.homeLeftThird) }
//            if (!UserInfoManager.isHaveDefPatient()) {
//                addPatientDialog()
//                return@onClick
//            }
//            IndependentBillingActivity.start(requireContext())
        }
        //左边第四个
        mBinding?.llSwitchPatients?.onClick {
//            PatientsActivity.start(requireContext())
            mainViewModel.homePageWarp.value?.let { it1 -> menuClick(it1.homeBottomFirst) }
        }
        //中间大广告图
        mBinding?.llInquiry?.onClick {
//            if (!UserInfoManager.isHaveDefPatient()) {
//                addPatientDialog()
//                return@onClick
//            }
//            DepartmentFragmentActivity.start(requireContext(), "inquiry")
            mainViewModel.homePageWarp.value?.let { it1 -> menuClick(it1.homeMainMenu) }

        }
        //右边第一个
        mBinding?.llNurse?.onClick {
//            if (!UserInfoManager.isHaveDefPatient()) {
//                addPatientDialog()
//                return@onClick
//            }
//            HomeCareActivity.start(requireContext())
            mainViewModel.homePageWarp.value?.let { it1 -> menuClick(it1.homeRightFirst) }
        }
        //右边第二个
        mBinding?.llBookingRegister?.onClick {
//            if (!UserInfoManager.isHaveDefPatient()) {
//                addPatientDialog()
//                return@onClick
//            }
//            DepartmentFragmentActivity.start(requireContext(), "booking")
            mainViewModel.homePageWarp.value?.let { it1 -> menuClick(it1.homeRightSecond) }

        }
        //右边第三个
        mBinding?.llMail?.onClick {
//            if (!UserInfoManager.isHaveDefPatient()) {
//                addPatientDialog()
//                return@onClick
//            }
//            IntelligentGuidanceActivity.start(requireContext())
            mainViewModel.homePageWarp.value?.let { it1 -> menuClick(it1.homeRightThird) }

        }
        //右边第四个
        mBinding?.llFollowing?.onClick {
//            if (!UserInfoManager.isHaveDefPatient()) {
//                addPatientDialog()
//                return@onClick
//            }
//            PrescriptionRecordActivity.start(requireContext())
            mainViewModel.homePageWarp.value?.let { it1 -> menuClick(it1.homeRightFourthly) }

        }


    }





    /**
     * 登录IM
     */
    private fun doLoginIM(patientBean: PatientBean) {
        val info = LoginInfo(patientBean.wyyxAccId, patientBean.wyyxToken)
        val callback: RequestCallback<LoginInfo?> = object : RequestCallback<LoginInfo?> {
            override fun onSuccess(param: LoginInfo?) {
                LogUtil.d("LoginInfo======onSuccess====")
                UserInfoManager.saveImUserAccount(param?.account)
                UserInfoManager.saveImToken(param?.token)
                showToast("就诊人登录成功")
            }

            override fun onFailed(code: Int) {


            }

            override fun onException(exception: Throwable) {

            }
        }
        //执行手动登录
        NIMClient.getService(AuthService::class.java).login(info).setCallback(callback)


    }


}
